import { defineStore } from 'pinia'
import { ref } from 'vue'
import axiosInstance from '../utils/request' // 假设您的 axios 实例在这里
import router from '../router' // 引入 router 用于导航
import { ElMessage } from 'element-plus'

interface UserInfo {
  id: number
  username: string
  email: string
  groups: string[] // 使用 groups 存储角色/用户组列表
  is_active: boolean
  last_login: string
  date_joined: string
}

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    // 尝试从 localStorage 恢复 userInfo
    userInfo: JSON.parse(localStorage.getItem('userInfo') || 'null') as UserInfo | null,
    isLoadingUserInfo: false,
  }),

  getters: {
    isLoggedIn: (state): boolean => !!state.token && !!state.userInfo,
    primaryRole: (state): string | undefined => {
        // 返回用户组列表中的第一个作为主要角色，如果没有则返回 undefined
        return state.userInfo?.groups?.[0];
    }
  },

  actions: {
    async login(username: string, password: string) {
      try {
        const response = await axiosInstance.post('/api/auth/login/', {
          username,
          password
        });
        
        const { token, user } = response.data;
        this.token = token;
        this.userInfo = user;
        
        // 保存token到localStorage
        localStorage.setItem('token', token);
        
        // 设置axios默认headers
        axiosInstance.defaults.headers.common['Authorization'] = `Bearer ${token}`;
        
        // 获取用户详细信息
        await this.fetchUserInfo();
        
        return true;
      } catch (error) {
        console.error('Login failed:', error);
        return false;
      }
    },

    setToken(token: string) {
      this.token = token
      localStorage.setItem('token', token)
    },

    setUserInfo(userInfo: UserInfo | null) {
        if (userInfo) {
            // 确保存储前 groups 是一个数组
            const infoToStore = { ...userInfo, groups: Array.isArray(userInfo.groups) ? userInfo.groups : [] };
            this.userInfo = infoToStore;
            localStorage.setItem('userInfo', JSON.stringify(infoToStore));
        } else {
            this.userInfo = null;
            localStorage.removeItem('userInfo');
        }
    },

    async fetchUserInfo() {
      if (this.isLoadingUserInfo || !this.token) {
          console.log('Skipping fetchUserInfo: already loading or no token');
          // 如果已经在加载，或者没有token，则不应继续，可能需要返回一个状态或Promise
          return Promise.resolve(); // 返回一个立即解决的Promise
      }
      this.isLoadingUserInfo = true;
      console.log('Fetching user info...');
      try {
        const response = await axiosInstance.get<UserInfo>('/api/auth/profile/');
        console.log('User info fetched:', response.data);
        // 在设置之前，再次确保 groups 是数组
        const userData = response.data;
        if(userData && !Array.isArray(userData.groups)) {
            console.warn('API response for groups is not an array, converting to empty array.');
            userData.groups = [];
        }
        this.setUserInfo(userData);
        return Promise.resolve(userData); // 返回获取到的数据
      } catch (error: any) {
        console.error('Failed to fetch user info:', error);
        this.clearUser();
        // 避免在这里重定向，让路由守卫处理导航
        // router.push('/login');
        return Promise.reject(error); // 返回拒绝的Promise
      } finally {
        this.isLoadingUserInfo = false;
        console.log('Finished fetching user info.');
      }
    },

    clearUser() {
      console.log('Clearing user state...');
      this.token = ''
      this.userInfo = null
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    },

    logout() {
      this.clearUser()
      // 登出后在调用处处理重定向
      // router.push('/login')
    },
  },
}) 